package com.guqj.thread.concurrent;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 多个异步任务执行，可以按任务完成顺序获取结果 CompletionService主要实现类是ExecutorCompletionService
 * </p>
 * 
 * @author guqj
 * @date 2017年3月13日
 */
public class CompletionServiceTest {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		new CompletionServiceTest().excute();
	}

	public void excute() throws InterruptedException, ExecutionException {
		ExecutorService ExecutorService = Executors.newFixedThreadPool(5);
		try {
			CompletionService<Integer> cs = new ExecutorCompletionService<>(ExecutorService,
					new ArrayBlockingQueue<Future<Integer>>(5));
			for (int i = 0; i < 5; i++) {
				cs.submit(new Task());
			}
			for (int i = 0; i < 5; i++) {
				Future<Integer> future = cs.take();
				if (null == future) {
					System.out.println("没发现有完成的任务");
				} else {
					System.out.println(future.get());
				}
			}
		} finally {
			ExecutorService.shutdown();
		}
	}
}

class Task implements Callable<Integer> {
	@Override
	public Integer call() throws InterruptedException {
		Random rand = new Random();
		TimeUnit.SECONDS.sleep(rand.nextInt(7));
		return rand.nextInt();
	}
}